const app = getApp()
const api = require('../../../api/index.js')
const util = require("../../../utils/util.js")
let col1H = 0
let col2H = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CAll:true,
    community: {
    },
    imgSrc: "",
    tokenState: false,
    pages: '',
    dataCommunity: {
      longitude: '116.3973900000',
      latitude: '39.9088600000',
      page: 1,
      type: 101,
      id: 101
    },
    setNum: 0,
    likeNum:'',
    community_id:'31',
    index:'朝阳区芍药居社区',
    noMore: false,
    empty:false,
    animationData: {},
    col1: [],
    col2: [],
    images: [],
    setIDs:1,
    onloade:false,
    classifyS:true
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      imgSrc: api.imgPathUrl //www.dicard.cn/Public/  api.imgPathUrl
    })
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    let key = wx.getStorageSync('key');
    let data;
    if (key == '') {
      data = that.data.dataCommunity
      wx.setStorageSync('key', {
        latitude: 39.9088600000 , 
        longitude: 116.3973900000
      })  
    } else {
      let lo = 'dataCommunity.longitude'
      let la = 'dataCommunity.latitude'
      that.setData({
        [lo]: key.longitude,
        [la]: key.latitude,
        page: ''
      })
      data = that.data.dataCommunity
    }
    this.dataIndex(data);
    
  },
  
  onImageLoad: function (e) {
    let imageId = e.currentTarget.id;
    let oImgW = e.detail.width;         //图片原始宽度
    let oImgH = e.detail.height;        //图片原始高度
    let imgWidth = 155.5;  //图片设置的宽度
    let scale = imgWidth / oImgW;        //比例计算
    let imgHeight = oImgH * scale;      //自适应高度
    let imageObj = null
    let images = this.data.community.article;
    for (let i = 0; i < images.length; i++) {   
      let img = images[i]
      if (images[i].note_id === imageId) {
        imageObj = img;
        break;
      }
    }
    let SN = this.data.setNum
    let loadingCount = this.data.loadingCount - 1;
    let col1 = this.data.col1;
    let col2 = this.data.col2;
    if (col1H <= col2H) {
      col1H += imgHeight;
      col1.push(imageObj);
    } else {
      col2H += imgHeight;
      col2.push(imageObj);
    }
    let data = {
      loadingCount: loadingCount,
      col1: col1,
      col2: col2
    };
    if (!loadingCount) {
      data.images = [];
    }
    this.setData(data);
    wx.hideLoading()
  },
  
  isUrl:function(){
    let community_id = this.data.community_id
    let sipk = this.data.index
    let tokenState = getApp().messages();
    let that = this
    if (tokenState === 0) {
      that.setData({
        tokenState: true
      })
    }else{
      wx.navigateTo({
        url: `/pages/community/issue/issue?id=${community_id}&&sipk=${sipk}`,
      })
    }
  },
  bindPickerChange: function(e) {
    let value = this.data.community.comm[e.detail.value].community_name
    let cid = this.data.community.comm[e.detail.value].community_id
    this.setData({
      index: value,
      community_id: cid
    })
    wx.setStorageSync('key',{
      community_id: cid
    })
  },
  classify: function (e) {
    let index = e.currentTarget.dataset.id
    let id = e.currentTarget.dataset.index
    let that = this;
    let community = 'community.article'
    let key = wx.getStorageSync('key');
    let nas = `dataCommunity.name`
    wx.showLoading({
      title: '加载中',
    })
    this.data.community.classify.forEach((item, index) => {
      let key = `community.classify[${index}].active`
      that.setData({
        [key]: false,
        [community]:'',
        setNum:1,
      })
    })
    this.setData({
      [`community.classify[${index}].active`]: true,
      noMore: false,
      [nas]:'',
      empty: false,
      setIDs: index,
      onloade: true
    
    })
    let typeID = `dataCommunity.type`
    let pages = `dataCommunity.page`
    let ids = `dataCommunity.id`
    this.setData({
      longitude: key.longitude,
      latitude: key.latitude,
      [typeID]: id,
      [pages]:1,
      [ids]:id,
    })

    let data = this.data.dataCommunity
    if (this.data.dataCommunity.id === 102){
      data.type = '102'
    }
    data.down = ''
    if (this.data.empty != true) {
      if (this.data.classifyS !=true){
        return false
      }
      this.data.col1.splice(0, this.data.col1.length)
      this.data.col2.splice(0, this.data.col2.length)
      this.setData({
        F12:true,
        classifyS:false
      })
    }
    setTimeout(() => {
      this.setData({
        onloade: false
      })
    }, 800)
    console.log(data)
    if (this.data.F12 == true){
      this.dataIndex(data, 1);
    }
    

   
  },
  searchBtn: function(event) {
    let name = event.detail.value
    if(name === ''){
      wx.showToast({
        title: '搜索不能是空哦',
        icon: "none",
      })
      return false
    }
    let nas = `dataCommunity.name`
    this.setData({
      [nas]: name
    })
    let data = {
      longitude: 116.3973900000,
      latitude: 39.9088600000,
      page: '',
      name: name
    
    }
    this.data.col1.splice(0, this.data.col1.length)
    this.data.col2.splice(0, this.data.col2.length)

    if (this.data.col1.length == '' && this.data.col2.length == '') {
      this.setData({
        col1: [],
        col2: []
      })
    }
    this.dataIndex(data);
    
  },
  // like: function(e) {
  //   let that = this
  //   let tokenState = getApp().messages();
  //   let index = e.currentTarget.dataset.inx
  //   let id = e.currentTarget.dataset.id
  //   console.log(index)
  //   let num = e.currentTarget.dataset.num
  //   console.log(tokenState)
  //   if (tokenState === 0) {
  //     that.setData({
  //       tokenState: true
  //     })
  //   } {
  //     num++;
  //     that.setData({
  //       [`community.article[${index}].agree_num`]: num
  //     })
  //   }
  //   let data = {
  //     note_id: id
  //   }
  //   setTimeout(()=>{
  //     api.like(data, (res) => {
  //       console.log(num, 456789, id)
  //     })
  //   },3000)
    
  // },
  dataUrl: function(e) {
    let note_id = e.currentTarget.dataset.id
    console.log(e, note_id)
    wx.navigateTo({
      url: `/pages/community/active/active?note_id=${note_id}`,
    })
  },

  lower: function() { // 上拉加载
    let onPullDown = this.data.onPullDown;
    var num 
    if (onPullDown == true){
      num = this.data.dataCommunity.page+1
    }else{
      num = this.data.dataCommunity.page 
    }
    
    num++;
    console.log(num)
    let ps = 'dataCommunity.page'
    this.setData({
      [ps]: num,
      onPullDown:false
    })
    let that = this
    let data = this.data.dataCommunity;
    data.type = this.data.dataCommunity.id
    data.down = ''
    console.log(data)
    if (this.data.noMore == false){
      api.communityIndex(data, (res) => {
        if (res.data.result.article.length == 0) {
          wx.showToast({
            title: '没有数据了',
            icon: "none",
          })
          setInterval(()=>{
            this.setData({
              CAll: false
            })
          },300)
          
          this.data.noMore = true;
        }
        console.log(res)
        this.data.noMore = false;
        let community = 'community.article'
        this.setData({
          [community]: this.data.community.article.concat(res.data.result.article)
         
        })

      })
    }

  },
  getPhoneNumber: function(e) {
    let sessionKeyS = wx.getStorageSync('session_key').session_key;
    console.log(sessionKeyS);
    if (sessionKeyS == '' || sessionKeyS == undefined) {
      app.Logins();
    }
    let invite_id = wx.getStorageSync('invite_id');
    let data = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      sessionKey: sessionKeyS,
      invite_id: invite_id
    }
    console.log(data);
    api.getPhoneNumber(data, (res) => {
      if (res.data.code == 50003) {
        this.setData({
          tokenState: true
        })
        wx.showToast({
          title: '亲，登录需要授权哦~',
          icon: 'none',
          duration: 2000
        })
      } else {
        this.setData({
          userData: res.data.result,
          tokenState: false
        })
        app.globalData.Refresh = true;
        wx.setStorageSync('token', {
          "token": res.data.result.token,
          "user_mobile": res.data.result.user_mobile
        });
        console.log(wx.getStorageSync('token'))
      }
    })
  },
  dataIndex: function(data,s) {
    api.communityIndex(data, (res) => {
      console.log(res.data.result)
      let AC = `community.article`
      let ACE = `community.classify[0].active`
      let typeids = 'dataCommunity.type'
      console.log(res.data.result.article.length)
      if (res.data.result.article.length == 0){
        this.setData({
          empty:true
        })
      }else{
        this.setData({
          empty: false
        })
      }

      if(s == 1){
        setTimeout(() => {
          this.setData({
            classifyS: true
          })
        }, 100)
        this.setData({
          [AC]: res.data.result.article,
          [typeids]: '',
          count: res.data.result.count
        })
      }else{
        this.setData({
          community: res.data.result,
          [typeids]: '',
          [ACE]:true,
          count : res.data.result.count
          
        })
      }
    })
    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
 
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
   
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
     
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let data = this.data.dataCommunity
    data.down = 1
    data.type = this.data.dataCommunity.id
    data.page = this.data.dataCommunity.page+1
    let cont = this.data.count

    this.setData({
      onPullDown:true
    })

    if (cont > 2 && cont > this.data.dataCommunity.page){
      this.data.col1.splice(0, this.data.col1.length)
      this.data.col2.splice(0, this.data.col2.length)
      this.RefreshS(data)
      this.setData({
        onloade: true
      })
    }else{
      wx.stopPullDownRefresh();
      wx.showToast({
        title: '已经是最新的',
        icon: 'none'
      })
    }
      
  },
  RefreshS:function(data){
    console.log(data)
    let AC = `community.article`
    api.Refresh(data,(res)=>{
      console.log(res)
      this.setData({
        [AC]: res.data.result.article.reverse(),
        count: res.data.result.count
      })
      wx.stopPullDownRefresh();
      setTimeout(() => {
            
        this.setData({
          onloade: false
        })
      }, 200)
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    this.lower();
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})